package api

import (
	"os"
	"strconv"
	"strings"

	"github.com/valyala/fasthttp"
	"gitlab.gaodun.com/golib/filetool"
	"permission/config/error_code"
)

func handRoot(ctx *fasthttp.RequestCtx) {
	SetApiCustomHeader(ctx)
	ctx.Write([]byte("{\"version\": \"1.0.0\"}"))
	return
}

func NotAllowCors(ctx *fasthttp.RequestCtx) {
	SetApiCustomHeader(ctx)
	ctx.Write([]byte("{\"status\":\"" + strconv.Itoa(error_code.NOT_ALLOW_CORS) + "\",\"info\": \"NotAllowCors\",\"data\":{}}"))
	return
}

func NotAllowIp(ctx *fasthttp.RequestCtx) {
	SetApiCustomHeader(ctx)
	ctx.Write([]byte("{\"status\":\"" + strconv.Itoa(error_code.NOT_ALLOW_IP) + "\",\"info\": \"IP not allow\",\"data\":{}}"))
	return
}

func SystemError(ctx *fasthttp.RequestCtx) {
	SetApiCustomHeader(ctx)
	ctx.Write([]byte("{\"status\":" + strconv.Itoa(error_code.SYS_ERR) + ",\"info\": \"system error\",\"data\":{}}"))
	return
}

func GetStatus(ctx *fasthttp.RequestCtx) {
	SetApiAllowCorsHeader(ctx)
	dir, _ := os.Getwd()
	fileOperate := filetool.FileOperate{Filename: dir + string(os.PathSeparator) + "DEPLOY"}
	if fileOperate.CheckFileExist(fileOperate.Filename) {
		text, _ := fileOperate.ReadFile(fileOperate.Filename)
		lineList := strings.Split(string(text), "\n")
		begin := "{"
		tmpStr := ""
		for _, line := range lineList {
			if len(line) == 0 {
				break
			}
			n := strings.Split(line, "|")
			jsonKey := "\"" + n[0] + "\""
			jsonValue := ":\"" + n[1] + "\""
			tmpStr += jsonKey + jsonValue + ","
		}
		mStr := strings.TrimRight(tmpStr, ",")
		end := "}"
		info := begin + mStr + end
		ctx.Write([]byte("{\"status\": \"1\",\"data\":" + info + "}"))
		return
	}

	ctx.Write([]byte("{\"status\": \"1\"}"))
	return

}
